let _listText = ref []
let _hashTblPath = ref (Hashtbl.create 101)

let fileExistInTextCode (textcode : GSourceView2.source_view) =
    try
        let path = Hashtbl.find !_hashTblPath textcode
        in (Sys.file_exists path)
    with Not_found -> false

    
let saveText pathS (textcode : GSourceView2.source_view)=
    if pathS = "dejaexistant" then
    let path = Hashtbl.find !_hashTblPath textcode in
    let code = open_out path in
    print_endline ("file : "^path^" Has been saved");
    output_string code (textcode#buffer#get_text ());
    close_out code; ()
    else
    let code = open_out pathS in
    print_endline ("file : "^pathS^" Has been saved");
    output_string code (textcode#buffer#get_text ());
    close_out code; ()

let cutPath str = 
    let reg = Str.regexp "/+" in
    let pathlist = (Str.split reg str) in
    List.nth pathlist ((List.length pathlist) - 1)

(* Apres s'etre fait basher par un 2009, on fait des trucs propres *)
let properCutPath path = 
  let i = String.rindex path '/' in
  String.sub path (i+1) (String.length path - i - 1) 
(*** Init ***)

let getPath textcode =  
	let path = Hashtbl.find !_hashTblPath textcode in
	properCutPath path

let deleteExtension path = 
	let i = ref 0 in
	let str = ref "" in
	while path.[!i] <> '.' do
	  i := !i+1;
	done;
	str := String.sub path 0 !i;
	!str

let cutDirPath path = 
  let i = String.rindex path '/' in
  String.sub path 0 (i+1) 

let cutSvnPath path =
  let rexp = Str.regexp "\\(.*/svn/\\).*" in
  Str.global_replace rexp "\\1" path

let loadText path source_view noteBookCode (textCode : GSourceView2.source_view) = 
  let text = open_in path in
  let length = in_channel_length text in
  let str = String.create length in
  if(source_view#getEndInit) && (noteBookCode#current_page = 0) then source_view#advanceMode textCode;
    really_input text str 0 length;
    close_in text;
  let current = noteBookCode#current_page in
    (List.nth noteBookCode#getListTabLabel current)#set_text (properCutPath path);
    let currentTextCode = (List.nth !_listText current) in
    currentTextCode#buffer#set_text (str);
    Hashtbl.add !_hashTblPath currentTextCode path
